package com.llyb.controller;

import com.llyb.service.McpService;
import dev.langchain4j.mcp.McpToolProvider;
import dev.langchain4j.mcp.client.DefaultMcpClient;
import dev.langchain4j.mcp.client.transport.stdio.StdioMcpTransport;
import dev.langchain4j.model.chat.StreamingChatModel;
import dev.langchain4j.service.AiServices;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.util.List;
import java.util.Map;

@RestController
@Slf4j
public class McpCallServerController {


    @Autowired
    private StreamingChatModel streamingChatModel;


    /**
     *
     * * 第1步，如何进行mcp编码
     *  * https://docs.langchain4j.dev/tutorials/mcp#creating-an-mcp-tool-provider
     *  *
     *  * 第2步，如何使用baidu map mcp，它提供了哪些功能对外服务
     *  * https://mcp.so/zh/server/baidu-map/baidu-maps?tab=tools
     *  *
     *  * http://localhost:9014/mcp/chat?question=查询61.149.121.66归属地
     *  * http://localhost:9014/mcp/chat?question=查询北京天气
     *  * http://localhost:9014/mcp/chat?question=查询昌平到天安门路线规划
     *
     * @param question
     * @return
     */
    // http://localhost:9014/mcp/chat
    @GetMapping("/mcp/chat")
    public Flux<String> chat(@RequestParam(value = "question")String question){
        StdioMcpTransport stdioMcpTransport = new StdioMcpTransport.Builder().
                command(List.of("cmd", "/c", "npx", "-y", "@baidumap/mcp-server-baidu-map")).
                environment(Map.of("BAIDU_MAP_API_KEY", System.getenv("BAIDU_MAP_API_KEY"))).
                build();

        DefaultMcpClient mcpClient = new DefaultMcpClient.Builder().
                transport(stdioMcpTransport).
                build();

        McpToolProvider mcpToolProvider = McpToolProvider.builder().mcpClients(mcpClient).build();

        McpService mcpService = AiServices.builder(McpService.class).
                streamingChatModel(streamingChatModel).
                toolProvider(mcpToolProvider).
                build();

        return mcpService.chat(question);


    }
}
